package controller

import (
	"demos/utils"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"net/http"
	"os"
	"strings"
)

// GetMinioUploadURL 生成MinIO预签名上传URL
func GetMinioUploadURL(c *gin.Context) {
	endpoint := os.Getenv("MINIO_ENDPOINT")
	accessKey := os.Getenv("MINIO_ACCESS_KEY")
	secretKey := os.Getenv("MINIO_SECRET_KEY")
	bucket := os.Getenv("MINIO_UPLOAD_BUCKET")

	// 获取文件后缀名
	ext := c.Param("ext")
	if ext != "" && !strings.HasPrefix(ext, ".") {
		ext = "." + ext
	}
	// 生成唯一objectName（无'-'，带后缀）
	objectName := strings.ReplaceAll(uuid.New().String(), "-", "") + ext

	client, err := utils.NewMinioClient(endpoint, accessKey, secretKey, false)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "MinIO连接失败"})
		return
	}

	// 生成预签名上传URL（600秒后过期）
	putUrl, err := utils.GetPresignedPutURL(client, bucket, objectName, 600)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成上传URL失败"})
		return
	}

	// 拼接公网访问路径
	publicHost := "http://" + endpoint
	publicUrl := ""
	if publicHost != "" {
		publicUrl = publicHost + "/" + bucket + "/" + objectName
	}

	c.JSON(http.StatusOK, gin.H{"url": putUrl, "objectName": objectName, "fileUrl": publicUrl})
}
